Ext.define('Admin.view.main.MainController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.main',

    requires: [
        'Ext.MessageBox'
    ],

    listen : {
        controller : {
            '#' : {
                unmatchedroute : 'setCurrentView'
            }
        }
    },

    routes: {
        ':node': 'setCurrentView',
        //c4w
        '(:en)detail/:id':{
            action     : 'showDetail'
        }
    },

    config: {
        showNavigation: true,
        //c4w
        control: {
            'ETasklist':{
            	openobj:'onOpenObj',
            	//editobj:'onEditObj'
            },
            'ETaskdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'Userlist':{
            	openobj:'onOpenObj',
            },
            'Userdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
       }

    },

    collapsedCls: 'main-nav-collapsed',
    //c4w
    showLogin:function(){
    	if(this.login)
			return;
		this.login = new DCApp.view.login.Login({
			session: this.session,
			autoShow: true,
			listeners: {
				scope: this,
				login: 'onLogin'
			}
        });
    },
    objNext:function(){    	
    	var inf = this.open_info;    	
     	var ds = inf.list.getStore();
     	var rec=inf.rec_next;
     	var pos = ds.indexOf(rec);
     	inf.rec_prev= inf.rec;
     	inf.rec=inf.rec_next;
     	inf.rec_next = ds.getAt(pos+1);
    	this.redirectTo(inf.nd + '/'+ rec.id);
    },
    objPrev:function(){
    	var inf = this.open_info;    	
     	var ds = inf.list.getStore();
     	var rec=inf.rec_prev;
     	var pos = ds.indexOf(rec);
     	inf.rec_next= inf.rec;
     	inf.rec=inf.rec_prev;
     	inf.rec_prev = ds.getAt(pos-1);
    	this.redirectTo(inf.nd + '/'+ rec.id);
    },
    
    viewObj:function(rec,id,detail_type,pinf){
        var me = this,
        view = this.getView(),
        item = view.child('component[routeId=' + detail_type + ']');
        var inf = pinf ||{};
        var data = {
            theObj: rec,
            showprev:Boolean(inf.rec_prev),
            shownext:Boolean(inf.rec_next),
            showsave:false,
            showpayCalculate:false,
            showreturn:inf.showsave
        };
        var vm = {
            data: data
        };
        if (!item) {
            item = view.add({
                xtype: detail_type,
                routeId: detail_type,
                viewModel:vm
            });
        }else{
            item.getViewModel().setData(data);      
        } 
        view.setActiveItem(item);
    },

    showDetail:function(p1,p2,p3){
		//console.log('showDetail:'+p1+":"+p3);
        var me=this;
        var pinf = me.open_info;
		if(pinf){   
            //TODO 向前/向后/返回／保存        
			return me.viewObj(pinf.rec,p3,pinf.nd,pinf);
		}
        var pdetail = p1+'detail';
        //TODO with login
		if(false && !Admin.Cfg.usrInfo){
			me.setOrigUri(pdetail+'/'+p3);
			return me.showLogin();
		}
		var className = 'Admin.model.'+Ext.String.capitalize(p1);
    	var modelClass = Ext.ClassManager.get(className);
    	//不符合detail命名规则的走VIP通道
    	if(!modelClass){
    		modelClass=Ext.ClassManager.get('Admin.model.'+detailCMap[p1]);
    	}
    	if(!modelClass)
    		return false;
    	var pm={};
    	pm[modelClass.idProperty||'id']=parseInt(p3);
    	var obj = modelClass.create(pm);
    	var me=this;
    	//Uses the configured RestProxy to make a GET request to /users/123
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,p3,pdetail);
    	    }
    	});
    	
    },
    onOpenObj:function(vw,rec,action){
    	//var vm = vw.getViewModel();
    	//var nd = this.getView().getXType().replace('detail','list');
    	var nl = vw.xtype;
     	var nd = nl.replace('list','detail');
     	var ds = vw.getStore();
     	var pos = ds.indexOf(rec);
     	if(pos==-1){
     		rec.set('id',-1);
     	}     	
     	this.open_info={
     		list:vw,
     		rec:rec,
     		nd:nd,nl:nl,
     		rec_prev : ds.getAt(pos-1),
     		rec_next : ds.getAt(pos+1),
     		scroll_y : vw.getTop(),
     		action:action
     	};
    	this.redirectTo(nd + '/'+ rec.id);
    },
    
    //c4w end

    onNavigationItemClick: function () {
        // The phone profile's controller uses this event to slide out the navigation
        // tree. We don't need to do anything but must be present since we always have
        // the listener on the view...
    },

    onNavigationTreeSelectionChange: function (tree, node) {
        var to = node && (node.get('routeId') || node.get('viewType'));

        if (to) {
            this.redirectTo(to);
        }
    },

    onSwitchToClassic: function () {
        Ext.Msg.confirm('Switch to Classic', 'Are you sure you want to switch toolkits?',
                        'onSwitchToClassicConfirmed', this);
    },

    onSwitchToClassicConfirmed: function (choice) {
        if (choice === 'yes') {
            var obj = Ext.Object.fromQueryString(location.search);

            delete obj.modern;

            obj.classic = '';

            location.search = '?' + Ext.Object.toQueryString(obj).replace('classic=', 'classic');
        } else {
            var button = this.lookup('toolkitSwitch');

            button.setValue(Ext.isModern ? 'modern' : 'classic');
        }
    },

    onToggleNavigationSize: function () {
        this.setShowNavigation(!this.getShowNavigation());
    },

    setCurrentView: function (hashTag) {
        hashTag = (hashTag || '').toLowerCase();

        var view = this.getView(),
            navigationTree = this.lookup('navigationTree'),
            store = navigationTree.getStore(),
            node = store.findNode('routeId', hashTag) ||
                   store.findNode('viewType', hashTag),
            item = view.child('component[routeId=' + hashTag + ']');

        if (!item) {
            item = {
                xtype: node.get('viewType'),
                routeId: hashTag
            };
        }

        view.setActiveItem(item);

        navigationTree.setSelection(node);
    },

    updateShowNavigation: function (showNavigation, oldValue) {
        // Ignore the first update since our initial state is managed specially. This
        // logic depends on view state that must be fully setup before we can toggle
        // things.
        //
        if (oldValue !== undefined) {
            var me = this,
                cls = me.collapsedCls,
                logo = me.lookup('logo'),
                navigation = me.lookup('navigation'),
                navigationTree = me.lookup('navigationTree'),
                rootEl = navigationTree.rootItem.el;

            navigation.toggleCls(cls);
            logo.toggleCls(cls);

            if (showNavigation) {
                // Restore the text and other decorations before we expand so that they
                // will be revealed properly. The forced width is still in force from
                // the collapse so the items won't wrap.
                navigationTree.setMicro(false);
            } else {
                // Ensure the right-side decorations (they get munged by the animation)
                // get clipped by propping up the width of the tree's root item while we
                // are collapsed.
                rootEl.setWidth(rootEl.getWidth());
            }

            logo.element.on({
                single: true,
                transitionend: function () {
                    if (showNavigation) {
                        // after expanding, we should remove the forced width
                        rootEl.setWidth('');
                    } else {
                        navigationTree.setMicro(true);
                    }
                }
            });
        }
    },

    toolbarButtonClick: function (btn) {
        var href = btn.config.href;

        this.redirectTo(href);
    }
});
